package com.xhui.vimarket.common.utils.obj;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

/**
 * @版权：福富软件 版权所有 (c) 2008
 * @文件：com.xhui.crm.common.util.obj.UtilDateConverter.java
 * @所含类：UtilDateConverter
 * @author: peilh
 * @version: V1.0
 * @see:
 * @创建日期：2008-8-23
 * @功能说明：
 * @修改记录： =============================================================<br>
 *        日期:2008-8-23 peilh 创建
 *        =============================================================<br>
 */
public class UtilDateConverter implements Converter {
    public UtilDateConverter() {
        
        this.defaultValue = null;
        this.useDefault = false;
        
    }
    
    public UtilDateConverter(final Object defaultValue) {
        
        this.defaultValue = defaultValue;
        this.useDefault = true;
        
    }
    
    private Object  defaultValue = null;
    
    private boolean useDefault   = true;
    
    public Object convert(final Class type, final Object value) {
        if (value == null) {
            return null;
        }
        
        if (value instanceof Date) {
            return (value);
        }
        
        final String strValue = value.toString();
        if (strValue == null) {
            return null;
        }
        if (strValue.equals("")) {
            return null;
        }
        Date theDate;
        
        if (strValue.length() > 10) {
            try {
                final String str = strValue.substring(4, 5);
                final SimpleDateFormat theFormat = new SimpleDateFormat("yyyy"
                    + str + "MM" + str + "dd" + " " + "HH" + ":" + "mm" + ":"
                    + "ss");
                theDate = theFormat.parse(strValue);
            } catch (final Exception ex) {
                if (this.useDefault) {
                    return (this.defaultValue);
                } else {
                    throw new ConversionException(ex);
                }
            }
        } else {
            try {
                final String str = strValue.substring(4, 5);
                final SimpleDateFormat theFormat = new SimpleDateFormat("yyyy"
                    + str + "MM" + str + "dd");
                theDate = theFormat.parse(strValue);
            } catch (final Exception ex) {
                if (this.useDefault) {
                    return (this.defaultValue);
                } else {
                    throw new ConversionException(ex);
                }
            }
        }
        
        return theDate;
        
    }
}
